<template>
  <div class="app-container home">
    <div class="bg_fff p_10 listbody">
      <div class="flexrowbetween flexwrapper" style="align-items: flex-start">
        <div class="flex">
          <div
            class="iconbox flexcenter commhover mr_10"
            @click="resetQuery"
          >
            <i class="el-icon-refresh f-20" :class="{ 'rotate': isrefresh }"></i>
          </div>
          <el-button plain type="primary" size="mini" @click="handleAdd"
            >添加</el-button
          >
          <el-button
            plain
            type="danger"
            :disabled="multiple"
            size="mini"
            @click="handleDelete"
            >删除</el-button
          >
        </div>
        <div>
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            label-width="0"
          >
            <el-form-item prop="keyword">
              <el-input
                class="searchinput"
                v-model="queryParams.keyword"
                placeholder="请输入素材名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item class="">
              <el-dropdown trigger="click">
                  <el-button size="mini" class="plr_9">
                    <svg-icon class-name="f-14" icon-class="listicon" />
                    <i class="el-icon-caret-bottom el-icon--right"></i>
                      <!-- <i class="el-icon-s-fold f-14"></i> -->
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                      <div class="dropbody">
                        <el-checkbox-group v-model="checkedOption" class="flexcolumn" @change="changeSelect">
                          <el-checkbox v-for="(item,index) in selectoptions" :label="item.label" :key="index" class="m_5">{{item.label}}</el-checkbox>
                        </el-checkbox-group>
                      </div>
                  </el-dropdown-menu>
              </el-dropdown>
            </el-form-item>
            <!-- <el-form-item>
              <el-dropdown trigger="click" @command="handleCommand">
                  <el-button size="mini" class="nol_border plr_9">
                    <svg-icon class-name="f-14" icon-class="export" />
                    <i class="el-icon-caret-bottom el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(item,index) in exportlist" :key="index" :command="item.id">{{item.name}}</el-dropdown-item>
                  </el-dropdown-menu>
              </el-dropdown>
            </el-form-item> -->
            <el-form-item>
              <el-button
                class="f-14"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
              ></el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        ref="tablelayout"
        class="commtable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column v-if="musicmaterialOption.includes('ID')"
          align="center"
          label="ID"
          prop="id"
          width="120"
        ></el-table-column>
        <el-table-column v-if="musicmaterialOption.includes('素材分类')"
          align="center"
          label="素材分类"
          prop="source_class.name"
        ></el-table-column>
        <el-table-column v-if="musicmaterialOption.includes('素材名称')"
          align="center"
          label="素材名称"
          prop="name"
        ></el-table-column>
        <!-- <el-table-column align="center" v-if="bgmaterialOption.includes('图片')" label="图片" width="200">
          <template slot-scope="scope">
            <el-image class="imgbox" :src="scope.row.img"  :preview-src-list="srcList"></el-image>
          </template>
        </el-table-column> -->
        <el-table-column v-if="musicmaterialOption.includes('排序')"
          align="center"
          label="排序"
          prop="level"
        ></el-table-column>
        <el-table-column label="显示素材" align="center" v-if="musicmaterialOption.includes('显示素材')">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#eee"
              :inactive-value="0"
              :active-value="1"
              @change="changeStatus($event,scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          prop="created_at"
          label="操作"
          width="160"
          fixed="right"
          align="center"
        >
          <template slot-scope="scope">
            <div class="flex btnflex">
              <div class="commhover btn_green c_fff mr_10"
                @click="handleSort(scope.row)"
              >
                <i class="el-icon-sort f-14"></i>排序
              </div>
              <div
                class="commhover btn_green c_fff"
                @click="handleUpdate(scope.row)"
              >
                <i class="el-icon-edit f-14"></i> 编辑
              </div>
              <!-- <div class="commhover btn_yellow c_fff"
                    @click="handleDelete(scope.row)">
                    <i class="el-icon-delete f-14"></i> 删除
                </div> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.num"
        @pagination="getList"
      />
    </div>
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="680px"
      class="dialogheaderbg"
      :before-close="handleCloseAdd"
      :close-on-click-modal='false'
    >
      <add-template v-if="open" :row='row' @close='handleCloseAdd'/>
    </el-dialog>
    <el-dialog
      title="排序"
      :visible.sync="opensort"
      width="500px"
      class="dialogheaderbg"
      :before-close="handleClosePx"
      :close-on-click-modal='false'
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="排序值" prop="level">
          <el-input v-model="form.level" placeholder="排序值（0-10000）" type="number" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleClosePx">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { getMusicIndex,musicStatusEdit,musicLevelEdit,musicDel } from '@/api/material'
import AddTemplate from './AddTemplate.vue';
export default {
  data() {
    return {
      queryParams: {
        page: 1,
        num: 10,
        keyword: undefined,
      },
      total: 0,
      loading: false,
      tableData: [],
      srcList:[],//
      checkedOption: [],
      isrefresh: false,
      selectoptions: [
        { id: 1, label: "ID" },
        { id: 2, label: "素材分类" },
        { id: 3, label: "素材名称" },
        { id: 5, label: "排序" },
        { id: 6, label: "显示素材" },
      ],
      dialogAddVisible: false,
      multiple: true,
      title: "",
      // 是否显示弹出层
      open: false,
      row:'',

      opensort:false,
      form:{
        id:undefined,
        level:"",
      },
      rules:{
        level: [
          { required: true, message: "排序值不能为空", trigger: "blur" }
        ],
      }
    };
  },

  props: {
    type: {
      type: Number,
      default: 1,
    },
  },

  components:{
    AddTemplate
  },

  computed: {
    ...mapState({
      musicmaterialOption: (state) => state.paramsoption.musicmaterialOption,
    }),
  },

  created() {
    let musicmaterialOption = JSON.parse(localStorage.getItem("musicmaterialOption"));
    if (musicmaterialOption) {
      this.changeSelect(musicmaterialOption);
    }
    this.checkedOption = this.musicmaterialOption;
    this.getList()
  },

  methods: {
    getList() {
      this.loading = true;
      let params = {
        page: this.queryParams.page,
        num: this.queryParams.num
      }
      if(this.queryParams.keyword){
        params.keyword = this.queryParams.keyword
      }
      getMusicIndex(params).then((response) => {
        this.tableData = response.data.list.map(item=>({...item,img:process.env.VUE_APP_BASE_API+'/'+item.url}));
        this.srcList = this.tableData.map(item=>(item.img))
        this.total = response.data.count;
      }).finally(()=>{
        this.loading = false;
        this.isrefresh = false;
      });
    },

    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },

    changeSelect(arr) {
      this.$store.commit("SET_MUSICMATERIALOPTION", arr);
      this.$nextTick(() => {
        //在数据加载完，重新渲染表格
        this.$refs.tablelayout && this.$refs.tablelayout.doLayout();
      });
    },

    resetQuery() {
      this.isrefresh = true;
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleSelectionChange(selection) {
      this.rowids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "添加";
    },

    handleCloseAdd(type) {
      if(type == 1){
        this.getList()
      }
      this.row = ''
      this.open = false;
    },

    handleCommand(command) {
      console.log(command);
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.row = row
      this.open = true;
      this.title = "修改";
    },

    changeStatus(val,row){
      let info = val?'显示':'隐藏'
      this.$modal.confirm('是否'+info+'素材').then(function() {
        return musicStatusEdit({
          id:row.id,
          status:val
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(val?"开启成功":'关闭成功');
      }).catch(() => {
        // console.log('jjjjjjj')
        row.status = val ? 0 : 1
      });
    },

    handleSort(row){
      this.form.id = row.id
      this.form.level = row.level
      this.opensort = true
    },

    handleClosePx(){
      this.opensort = false
    },

    submitForm(){
      this.$refs.form.validate(valid=>{
        if(!valid) return
        musicLevelEdit(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.handleClosePx()
          this.getList();
        });
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const infoIds = row.id || this.rowids;
      this.$modal
        .confirm('是否确认删除访问编号为"' + infoIds + '"的数据项？')
        .then(function () {
          return musicDel({id:infoIds});
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.iconbox {
  width: 32px;
  height: 32px;
  border: 1px solid #eee;
  border-radius: 2px;
}
.imgbox {
  width: 120px;
  height: 50px;
}
</style>
